package com.yuncheng.spcyApi.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.sys.SysConfigConstant;
import com.yuncheng.spcyApi.entity.SysConfig;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.spcyApi.service.ISysConfigService;
import com.yuncheng.spcyApi.service.IYcSysUserService;
import com.yuncheng.spcyApi.utils.SmsUtils;
import com.yuncheng.spcyApi.utils.ValidateCodeUtils;
import com.yuncheng.vo.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "审评查验-登录短信接口")
@RestController
@RequestMapping("/api/spzx-spcy/loginSms")
public class LoginSmsController {
    private static final Logger log = LoggerFactory.getLogger(LoginSmsController.class);

    @Resource
    private IYcSysUserService ycSysUserService;

    @Resource
    private ISysConfigService sysConfigService;

    @Resource
    private SmsUtils smsUtils;

    @Log(title = "获取短信验证码")
    @ApiOperation(value = "获取短信验证码")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "username",value = "账号"),
            @ApiImplicitParam(name = "password",value = "密码")
    })
    @PostMapping(value = "getSmsCode")
    public HttpResult<?> getSmsCode(@RequestBody Map<String,String> map){
        String username = map.get("username");
        String pwd = map.get("password");
        if (StringUtils.isBlank(username)){
            return HttpResult.error("请输入账号");
        }
        if (StringUtils.isBlank(pwd)){
            return HttpResult.error("请输入密码");
        }

        YcSysUser user = null;
        String phone = "";

        // 当前用户(目前只有账号验证、密码验证后续加)
        List<YcSysUser> userList = ycSysUserService.list(new LambdaQueryWrapper<YcSysUser>().eq(YcSysUser::getUsername, username));
        if (CollectionUtils.isEmpty(userList)){
            return HttpResult.error("当前账号不存在");
        }else {
            user = userList.get(0);

            // 判断是否在有效时间发送
            if (user.getDlyzmkzcfssj() != null) {
                Date dlyzmkzcfssj = user.getDlyzmkzcfssj();// 可再次发送验证码时间
                DateTime nowDate = DateUtil.date();
                boolean before = nowDate.before(dlyzmkzcfssj);
                if (before) {
                    long ms = (dlyzmkzcfssj.getTime() - nowDate.getTime()) / 1000; // 剩余秒数
                    return HttpResult.error("发送验证码失败，请在" + ms + "秒后再次进行发送。");
                }
            }
        }

        if (StringUtils.isBlank(user.getPhone())){
            return HttpResult.error("当前账号，电话号码为空");
        }else {
            phone = user.getPhone();
        }

        // 发送短信验证码内容
        StringBuffer smMsg = new StringBuffer("广西审评查验信息一体化智慧管理系统登录验证码：");

        // 随机生成四位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        String yxsj = "1"; // 验证码有效时间
        String jgsj = "1"; // 再次发送短信-间隔时间
        Date nowTime = null;  // 当前时间
        Integer djs = 60; // 间隔时间

        // 获取系统-再次发送短信-间隔时间
        List<SysConfig> againLoginMsgMinute = sysConfigService.list(new LambdaQueryWrapper<SysConfig>()
                .eq(SysConfig::getConfigCode, SysConfigConstant.Send_Again_Login_Msg_Minute));
        if (CollectionUtils.isNotEmpty(againLoginMsgMinute)){
            jgsj = againLoginMsgMinute.get(0).getConfigValue();
        }

        // 获取系统-验证码有效时间
        List<SysConfig> configMinute = sysConfigService.list(new LambdaQueryWrapper<SysConfig>()
                .eq(SysConfig::getConfigCode, SysConfigConstant.Login_Pass_Code_Minute));
        if (CollectionUtils.isNotEmpty(configMinute)){
            yxsj = configMinute.get(0).getConfigValue();
        }

        smMsg.append(code);
        smMsg.append(";").append("有效时间").append(yxsj).append("分钟");
        try {
            String flag = "";
            if (username.equalsIgnoreCase("admin")) {
                // 管理员
                flag = smsUtils.sendSmsCase(phone, smMsg.toString());
            }else {
                flag = smsUtils.sendSms(phone, smMsg.toString());
            }
            // 发送短信成功
            if (flag.contains(SysConfigConstant.SMS_FLAG)){
                log.info("发送短信验证码成功");

                nowTime = DateUtil.date(); // 当前时间

                Integer jgsjByIn = Integer.valueOf(jgsj);
                djs = jgsjByIn * 60; // 可再次发送时间(秒)

                Integer yxsjByIn = Integer.valueOf(yxsj);

                Date dlyzmkzcscsjTime = DateUtil.offsetMinute(nowTime, jgsjByIn); // 可再次发送时间

                Date dlyzmyxjzsjTime = DateUtil.offsetMinute(nowTime, yxsjByIn); // 验证码有效截止时间

                user.setDlyzm(code);
                user.setDlyzmscsj(nowTime);
                user.setDlyzmkzcfssj(dlyzmkzcscsjTime);
                user.setDlyzmyxjzsj(dlyzmyxjzsjTime);
                ycSysUserService.updateById(user); // 更新用户验证码

            }else {
                return HttpResult.error("发送短信失败，请刷新重试");
            }
        } catch (NoSuchAlgorithmException e) {
            log.error("发送短信失败【NoSuchAlgorithmException】: {}",e.getMessage());
        } catch (IOException e) {
            log.error("发送短信失败【NoSuchAlgorithmException】: {}",e.getMessage());
        } catch (InvalidKeySpecException e) {
            log.error("发送短信失败【NoSuchAlgorithmException】: {}",e.getMessage());
        }

        Map resultMap = new HashMap<>();
        resultMap.put("djs",djs.toString()); // 可再次发送验证码倒计时（秒）
        return HttpResult.ok(resultMap);
    }

    @Log(title = "获取是否开启短信验证")
    @ApiOperation(value = "获取是否开启短信验证")
    @GetMapping(value = "getEnableSmsValidate")
    public HttpResult<?> getEnableSmsValidate(){
        // true(开启验证码)、false（不开启）
        boolean flag = false;

        // 获取系统参数-是否开启短信验证
        List<SysConfig> config = sysConfigService.list(new LambdaQueryWrapper<SysConfig>()
                .eq(SysConfig::getConfigCode, SysConfigConstant.Flag_login_Msg_Code));

        if (CollectionUtils.isNotEmpty(config)){
            String configValue = config.get(0).getConfigValue();

            if(StringUtils.isNotBlank(configValue) && configValue.trim().equals("1")){
                flag = true;
            }else {
                flag = false;
            }
        }

        Map resultMap = new HashMap();
        resultMap.put("flag",flag);
        return HttpResult.ok(resultMap);
    }

    @Log(title = "验证输入的验证码")
    @ApiOperation(value = "验证输入的验证码")
    @GetMapping(value = "validateLoginCode")
    public HttpResult<?> validateLoginCode(@RequestParam("username")String username,@RequestParam("code")String code){
        if (StringUtils.isBlank(username)){
            return HttpResult.error("请输入账号");
        }
        // 当前用户(目前只有账号验证、密码验证后续加)
        List<YcSysUser> userList = ycSysUserService.list(new LambdaQueryWrapper<YcSysUser>().eq(YcSysUser::getUsername, username));
        if (CollectionUtils.isEmpty(userList)){
            return HttpResult.error("当前账号不存在");
        }
        YcSysUser user = userList.get(0);
        String dlyzm = user.getDlyzm();
        if (StringUtils.isBlank(dlyzm)){
            return HttpResult.error("请先发送短信验证码");
        }
        if (!dlyzm.equals(code)){
            return HttpResult.error("验证码错误");
        }

        return HttpResult.ok("验证码正确");
    }

    /**
     * 获取短信验证码通行码
     */
    public String getLoginPassCode(){
        String passCode = "";

        // 获取短信验证码通行码
        List<SysConfig> config = sysConfigService.list(new LambdaQueryWrapper<SysConfig>()
                .eq(SysConfig::getConfigCode, SysConfigConstant.Login_Pass_Code));

        if (CollectionUtils.isEmpty(config)){
            passCode = config.get(0).getConfigValue();
        }

        return passCode;
    }
}
